package com.shiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Autowired
    private UserRealm userRealm;

    //1、创建UserRealm 需自定义类
    @Bean
    public UserRealm getUserRealm(){
        return new UserRealm();
    }

    //2、DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //3、ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /**
         * anon：无需认证即可访问
         * authc：必须认证才能访问
         * user：必须拥有记住我功能才能用
         * perms：拥有对某个资源的权限才能访问
         * role：拥有某个角色权限才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        //必须认证才能访问
//        filterMap.put("/user/addUser","authc");
//        filterMap.put("/user/updateUser","authc");
        filterMap.put("/user/addUser","perms[user:add]");
        filterMap.put("/user/updateUser","perms[user:update]");
        filterMap.put("/user/**","perms[user]");
        bean.setFilterChainDefinitionMap(filterMap);
        //设置未登录时跳到登录页面
        bean.setLoginUrl("/tologin");
        //未经授权无法访问跳转页面
        bean.setUnauthorizedUrl("/unauth");
        return bean;
    }

    //shiro整合thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
